"""
自定义入参处理示例
"""
from flask import request, jsonify
from functools import wraps
from marshmallow import Schema, fields, validate, ValidationError
import json


def validate_json(schema_class):
    """
    装饰器：验证JSON请求体
    """
    def decorator(f):
        @wraps(f)
        def decorated_function(*args, **kwargs):
            try:
                # 解析JSON数据
                json_data = request.get_json()
                if not json_data:
                    return jsonify({
                        "code": 400,
                        "message": "请求体必须是有效的JSON",
                        "data": None
                    }), 400
                
                # 使用schema验证数据
                schema = schema_class()
                data = schema.load(json_data)
                
                # 将验证后的数据添加到请求上下文
                request.validated_data = data
                
                return f(*args, **kwargs)
            except ValidationError as err:
                return jsonify({
                    "code": 400,
                    "message": "数据验证失败",
                    "data": err.messages
                }), 400
            except Exception as e:
                return jsonify({
                    "code": 500,
                    "message": f"服务器错误: {str(e)}",
                    "data": None
                }), 500
        return decorated_function
    return decorator


def validate_query_params(schema_class):
    """
    装饰器：验证查询参数
    """
    def decorator(f):
        @wraps(f)
        def decorated_function(*args, **kwargs):
            try:
                # 获取查询参数
                query_data = dict(request.args)
                
                # 转换数据类型
                for key, value in query_data.items():
                    # 尝试转换为整数
                    if value.isdigit():
                        query_data[key] = int(value)
                    # 尝试转换为布尔值
                    elif value.lower() in ('true', 'false'):
                        query_data[key] = value.lower() == 'true'
                
                # 使用schema验证数据
                schema = schema_class()
                data = schema.load(query_data)
                
                # 将验证后的数据添加到请求上下文
                request.validated_query = data
                
                return f(*args, **kwargs)
            except ValidationError as err:
                return jsonify({
                    "code": 400,
                    "message": "查询参数验证失败",
                    "data": err.messages
                }), 400
            except Exception as e:
                return jsonify({
                    "code": 500,
                    "message": f"服务器错误: {str(e)}",
                    "data": None
                }), 500
        return decorated_function
    return decorator


# 使用Marshmallow定义数据验证模式
class UserRegistrationSchema(Schema):
    """用户注册数据验证模式"""
    email = fields.Email(required=True, validate=validate.Length(max=120))
    username = fields.Str(required=True, validate=validate.Length(min=3, max=80))
    password = fields.Str(required=True, validate=validate.Length(min=6, max=128))
    confirm_password = fields.Str(required=True)
    
    def validate(self, data, **kwargs):
        """自定义验证：确认密码匹配"""
        if data.get('password') != data.get('confirm_password'):
            raise ValidationError("密码和确认密码不匹配")
        return data


class UserLoginSchema(Schema):
    """用户登录数据验证模式"""
    email = fields.Email(required=True)
    password = fields.Str(required=True)


class UserQuerySchema(Schema):
    """用户查询参数验证模式"""
    page = fields.Int(missing=1, validate=validate.Range(min=1))
    per_page = fields.Int(missing=10, validate=validate.Range(min=1, max=100))
    is_active = fields.Bool(missing=None)
    is_admin = fields.Bool(missing=None)
    search = fields.Str(missing="", validate=validate.Length(max=100))


# 使用示例
@validate_json(UserRegistrationSchema)
def register_user():
    """注册用户示例"""
    data = request.validated_data
    
    # 从验证后的数据中提取字段
    email = data['email']
    username = data['username']
    password = data['password']
    
    # 在这里处理用户注册逻辑
    # ...
    
    return jsonify({
        "code": 201,
        "message": "用户注册成功",
        "data": {
            "email": email,
            "username": username
        }
    }), 201


@validate_json(UserLoginSchema)
def login_user():
    """用户登录示例"""
    data = request.validated_data
    
    email = data['email']
    password = data['password']
    
    # 在这里处理用户登录逻辑
    # ...
    
    return jsonify({
        "code": 200,
        "message": "登录成功",
        "data": {
            "access_token": "示例token",
            "refresh_token": "示例refresh_token"
        }
    }), 200


@validate_query_params(UserQuerySchema)
def get_users():
    """获取用户列表示例"""
    query = request.validated_query
    
    page = query['page']
    per_page = query['per_page']
    is_active = query['is_active']
    is_admin = query['is_admin']
    search = query['search']
    
    # 在这里处理获取用户列表逻辑
    # ...
    
    return jsonify({
        "code": 200,
        "message": "获取用户列表成功",
        "data": {
            "users": [],  # 示例用户数据
            "pagination": {
                "page": page,
                "per_page": per_page,
                "total": 0,
                "pages": 0
            }
        }
    }), 200